package com.losdun.product.utils;

import java.util.*;
import java.util.stream.Collectors;
/**
 * @Author sword.ye
 * @Date 2025/2/28
 * @Description
 */

public class CartesianProductUtils {

    /**
     * 计算多个集合的笛卡尔积（通用实现）
     * @param lists 输入集合列表
     * @return 所有可能的组合列表
     */
    public static <T> List<List<T>> calculate(List<List<T>> lists) {
        if (lists == null || lists.isEmpty()) {
            return Collections.emptyList();
        }
        return cartesianProduct(lists, 0);
    }

    private static <T> List<List<T>> cartesianProduct(List<List<T>> lists, int index) {
        List<List<T>> result = new ArrayList<>();
        if (index == lists.size()) {
            result.add(new ArrayList<>());
            return result;
        }

        List<T> currentList = lists.get(index);
        List<List<T>> remainingCombinations = cartesianProduct(lists, index + 1);

        for (T element : currentList) {
            for (List<T> combination : remainingCombinations) {
                List<T> newCombination = new ArrayList<>();
                newCombination.add(element);
                newCombination.addAll(combination);
                result.add(newCombination);
            }
        }
        return result;
    }

    /**
     * 针对字符串属性的优化实现
     * @param attributes 属性键值对（属性名 -> 属性值列表）
     * @return 属性组合列表（每个Map对应一种SKU的属性集合）
     */
    public static List<AttributeCombination> generateAttributeCombinations(
            Map<String, List<String>> attributes
    ) {
        List<List<String>> valueLists = new ArrayList<>();
        List<String> keys = new ArrayList<>(attributes.keySet());

        for (String key : keys) {
            valueLists.add(attributes.get(key));
        }

        List<List<String>> product = calculate(valueLists);
        return product.stream()
                .map(values -> {
                    Map<String, String> map = new LinkedHashMap<>();
                    for (int i = 0; i < keys.size(); i++) {
                        map.put(keys.get(i), values.get(i));
                    }
                    return new AttributeCombination(map);
                })
                .collect(Collectors.toList());
    }

    /**
     * 属性组合包装类（用于生成SKU）
     */
    public static class AttributeCombination {
        private final Map<String, String> attributes;

        public AttributeCombination(Map<String, String> attributes) {
            this.attributes = attributes;
        }

        public Map<String, String> getAttributes() {
            return Collections.unmodifiableMap(attributes);
        }

        public String getHash() {
            return attributes.values().stream()
                    .sorted()
                    .collect(Collectors.joining("|"));
        }
    }


}